package com.woniu.teachmall04.service;

import com.woniu.teachmall04.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final String GOODS_PAGE_KEY = "goods:page:";
    private static final long CACHE_EXPIRE_TIME = 30; // 分钟

    public void cacheGoodsPage(int page, List<Goods> goods) {
        String key = GOODS_PAGE_KEY + page;
        redisTemplate.opsForValue().set(key, goods, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
    }

    public List<Goods> getCachedGoodsPage(int page) {
        String key = GOODS_PAGE_KEY + page;
        return (List<Goods>) redisTemplate.opsForValue().get(key);
    }

    public void deleteCache(int page) {
        redisTemplate.delete(GOODS_PAGE_KEY + page);
    }
    private static final String GOODS_CACHE_PREFIX = "goods:cache:";

    public List<Goods> getCachedGoodsPage(String cacheKey) {
        return (List<Goods>) redisTemplate.opsForValue().get(GOODS_CACHE_PREFIX + cacheKey);
    }

    public void cacheGoodsPage(String cacheKey, List<Goods> goods) {
        redisTemplate.opsForValue().set(
                GOODS_CACHE_PREFIX + cacheKey,
                goods,
                30, // 30分钟过期
                TimeUnit.MINUTES
        );
    }

    public void clearGoodsCache() {
        Set<String> keys = redisTemplate.keys(GOODS_CACHE_PREFIX + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}
